package im.ok.back.controller;

import cn.hutool.core.util.IdUtil;
import com.google.zxing.WriterException;
import im.ok.back.common.FileSuffixEnum;
import im.ok.back.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("QRCode")
public class QRCodeController {

    @PostMapping("getQRCodeImage")
    public void getQRCodeImage(String textarea, HttpServletResponse response) {
        try {
            ApplicationHome h = new ApplicationHome(CommonUtil.class);
            File source = h.getSource();
            String s = source.getParentFile().toString();

            String tempPath = "";
            String uuid = IdUtil.simpleUUID();
            if (CommonUtil.isOsWin()) {
                tempPath = s + "\\" + uuid + ".png";
            } else {
                tempPath = s + "/" + uuid + ".png";
            }
            CommonUtil.generateQRCodeImage(textarea, 360, 360, tempPath);
            // 导出二维码图片流
            CommonUtil.doExport(s, uuid, FileSuffixEnum.PNG.getDesc(), response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (WriterException e) {
            throw new RuntimeException(e);
        }

    }
}
